﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using FileDB;

namespace Rem.Objects.Forms
{
    public partial class ReminderForm2 : BaseForm
    {
        public const string TextTemplate = "提醒#{0}-{1}";
        private Reminder _reminder { get; set; }
        List<Reminder> _reminders = new List<Reminder>();
        public List<Reminder> Reminders { get { return _reminders; } }
        public event EventHandler _generateReminders;

        public ReminderForm2(Reminder reminder)
        {
            InitializeComponent();
            if (reminder == null)
                throw new ArgumentException("reminder should not be null", "reminder");
            this._reminder = reminder;

            this.nameComboBox.Items.Add(ReminderCategory.GetReminder);
            this.nameComboBox.Items.Add(ReminderCategory.PostReminder);
            this.nameComboBox.Items.Add(ReminderCategory.ImportantReminder);
            this.nameComboBox.Items.Add(ReminderCategory.RenewReminder);
            this.statusComboBox.Items.Add(ReminderState.Actived);
            this.statusComboBox.Items.Add(ReminderState.Finished);
            this.nameComboBox.SelectedIndex = 0;
            this.statusComboBox.SelectedIndex = 0;
            DisplayInfo();
        }

        public ReminderForm2()
            : this(new Reminder())
        { }

        private void DisplayInfo()
        {
            this.Text = string.Format(TextTemplate, _reminder.Id, _reminder.Category);
            if (this._reminder != null && this._reminder.Id > 0)
            {
                this.statusComboBox.Text = this._reminder.Status;
                this.contractNoLinkLabel.Enabled = false;

                this.advanceDaysUpDown.Visible = false;
                this.label1.Visible = false;
                this.label3.Visible = false;
            }
            else
            {
                this.advanceDaysUpDown.Visible = true;
                this.label1.Visible = true;
                this.label3.Visible = true;
                this.lblID.Text = QueryConstants.UnsavedObjectId.ToString();
            }

            if (_reminder != null)
            {
                this.messageTextBox.Text = this._reminder.Message;
                this.nameComboBox.Text = this._reminder.Category;
                this.statusComboBox.Text = _reminder.Status;
                this.reminderTimeDateTimePicker.Value = _reminder.ReminderTime;
                this.startDateTimePicker.Value = _reminder.StartTime;
                this.dueTimeDateTimePicker.Value = _reminder.DueTime;
            }
            if (this._reminder != null && this._reminder.ContractId > 0)
            {
                Contract contract = Contract.GetContract(this._reminder.ContractId);
                this.contractNoLinkLabel.Text = contract.Address;
                this.contractNoLinkLabel.Tag = contract;
                this.associategroupBox.Visible = true;
                this.contractNoLinkLabel.Enabled = true;
            }

            lblID.Text = string.Format(QueryConstants.IDTemplate, this._reminder.Id.ToString());
        }

        //public ReminderForm2(string text, Contract contract)
        //{
        //    InitializeComponent();

        //    this.Text = text;
        //    this.nameComboBox.Items.Add(ReminderCategory.GetReminder);
        //    this.nameComboBox.Items.Add(ReminderCategory.PostReminder);
        //    this.nameComboBox.Items.Add(ReminderCategory.ImportantReminder);
        //    this.nameComboBox.Items.Add(ReminderCategory.RenewReminder);
        //    this.nameComboBox.Items.Add(ReminderCategory.OtherReminder);
        //    this.statusComboBox.Items.Add(ReminderState.Newed);
        //    this.statusComboBox.Items.Add(ReminderState.Finished);
        //    this._reminder = new Reminder() ;
        //    if (contract != null)
        //    {
        //        this._reminder.ContractId = contract.Id;
        //    }
        //    DisplayInfo();
        //}

        public event EventHandler GenerateReminders
        {
            add
            {
                this._generateReminders += value;
            }
            remove
            {
                this._generateReminders -= value;
            }
        }

        public override BaseObjectTypes BaseType
        {
            get
            {
                return BaseObjectTypes.Reminder;
            }
        }

        public static void NewPeriodRemind()
        {
            ReminderForm2 form = new ReminderForm2() { Text = "生成周期提醒" };
            form.periedgroupBox.Visible = true;
            form.Dock = DockStyle.Fill;
            form.GenerateReminders += (source, arg) =>
            {
                IEnumerable<Reminder> reminders = source as IEnumerable<Reminder>;
                if (reminders != null)
                {
                    QueryForm.OpenReminderQuery(0, "周期提醒", reminders);
                }
            };
        }

        private void deleteToolStripButton_Click(object sender, EventArgs e)
        {

        }


        //public void GeneratePeriodReminder(Reminder remider, int advancedDays, int interval)
        //{
        //    this._reminders = new List<Reminder>();
        //    Guid batch = Guid.NewGuid();
        //    Contract contract = this.contractNoLinkLabel.Tag as Contract;

        //    DateTime start = remider.StartTime;
        //    DateTime end = remider.DueTime;
        //    int delta = (remider.ReminderTime - start).Days - advancedDays;

        //    this._reminders.Clear();
        //    while (start < end)
        //    {
        //        Reminder r = new Reminder();
        //        r.Category = remider.Category;
        //        r.Status = remider.Status;
        //        r.BatchId = batch.ToString();
        //        r.CreatedTime = remider.CreatedTime;
        //        r.Message = remider.Message;
        //        r.ContractId = remider.ContractId;
        //        if (start.AddMonths(interval).AddDays(-1) < end)
        //        {

        //            r.StartTime = start;
        //            r.ReminderTime = start.AddDays(delta);
        //            r.DueTime = start.AddMonths(interval).AddDays(-1);
        //            start = start.AddMonths(interval);
        //            if (string.IsNullOrEmpty(remider.Message) && remider.ContractId > 0)
        //            {
        //                r.Message = string.Format("地址:{0} 收租方:{1} 缴租方: {2} 金额:{3} 起止日期: {4}到{5} 开票:{6}",
        //                    contract.Address,
        //                    Customer.GetCustomer(contract.PartAId).Name,
        //                    Customer.GetCustomer(contract.PartBId).Name,
        //                    (contract.RentPerInterval * interval).ToString("8d"),
        //                    r.StartTime.Date.ToString(),
        //                    r.DueTime.Date.ToString(),
        //                    contract.CanTicket ? "是" : "否"
        //                    );
        //            }
        //        }
        //        else
        //        {
        //            r.StartTime = start;
        //            r.ReminderTime = start.AddDays(delta);
        //            r.DueTime = end;
        //            start = end.AddDays(1);
        //            if (string.IsNullOrEmpty(remider.Message) && remider.ContractId > 0)
        //            {
        //                int months = 0;
        //                int days = 0;
        //                while (months < interval)
        //                {
        //                    if (start.AddMonths(months + 1).AddDays(-1) < end)
        //                    {
        //                        months++;
        //                    }
        //                    else
        //                    {
        //                        break;
        //                    }
        //                }
        //                days = (end - start.AddMonths(months)).Days;

        //                r.Message = string.Format("地址:{0} 收租方:{1} 缴租方: {2} 金额:{3} 起止日期: {4}到{5} 开票:{6}",
        //                    contract.Address,
        //                    Customer.GetCustomer(contract.PartAId).Name,
        //                    Customer.GetCustomer(contract.PartBId).Name,
        //                    (contract.RentPerInterval * months + contract.RentPerInterval * days / 30).ToString("d8"),
        //                    r.StartTime.Date.ToString(),
        //                    r.DueTime.Date.ToString(),
        //                    contract.CanTicket ? "是" : "否"
        //                    );
        //            }
        //        }
        //        this._reminders.Add(r);
        //    }
        //}
        private void saveToolStripButton_Click(object sender, EventArgs e)
        {

        }

        private bool GetReminder()
        {
            Contract contract = Contract.GetContract(_reminder.ContractId);
            if (string.IsNullOrWhiteSpace(this.messageTextBox.Text) && contract == null)
            {
                MessageBox.Show("信息为空！请输入信息！");
                return false;
            }
            if (this.startDateTimePicker.Value > this.dueTimeDateTimePicker.Value)
            {
                MessageBox.Show("开始日期大于等于结束日期！");
                return false;
            }

            this._reminder.Message = this.messageTextBox.Text;


            this._reminder.DueTime = this.dueTimeDateTimePicker.Value;
            this._reminder.CreatedTime = DateTime.Now;
            this._reminder.StartTime = this.startDateTimePicker.Value;
            
            this._reminder.Category = this.nameComboBox.Text;
            this._reminder.Status = this.statusComboBox.Text;

            if (this.advanceDaysUpDown.Visible)
            {
                this._reminder.ReminderTime = this.reminderTimeDateTimePicker.Value.AddDays(-Int32.Parse(this.advanceDaysUpDown.Value.ToString()));
            }
            else
            {
                this._reminder.ReminderTime = this.reminderTimeDateTimePicker.Value;
            }
            if (contract != null)
            {
                this._reminder.ContractId = contract.Id;
            }
            return true;
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (this._reminder == null || this._reminder.Id < 1)
                return;
            try
            {
                Cursor.Current = Cursors.Arrow;
                this._reminder.Status = ReminderState.Finished;
                Reminder.Update(this._reminder);
            }
            catch (Exception ex)
            {
                Logger.WriteError(BaseObjectTypes.Reminder, this._reminder, ex);
                MessageBox.Show("", "", MessageBoxButtons.OK);
            }

            finally
            {
                Cursor.Current = Cursors.Default;

            }
            DisplayInfo();
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            if (this._reminder == null || this._reminder.Id < 1)
                return;
            try
            {
                Cursor.Current = Cursors.Arrow;
                this._reminder.Status = ReminderState.Actived;
                Reminder.Update(this._reminder);
            }
            catch (Exception ex)
            {
                Logger.WriteError(BaseObjectTypes.Reminder, this._reminder, ex);
                MessageBox.Show("", "", MessageBoxButtons.OK);
            }

            finally
            {
                Cursor.Current = Cursors.Default;

            }
            DisplayInfo();
        }

        private void contractNoLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (this.contractNoLinkLabel.Tag is Contract)
            {
                Contract c = this.contractNoLinkLabel.Tag as Contract;
                if (c.Id > 0)
                {
                    ContractForm f = new ContractForm(c);
                    f.Show();
                    f.Dock = DockStyle.Fill;
                }
            }
            else
            {
                ObjectPickerForm picker = new ObjectPickerForm(BaseObjectTypes.Contract);
                picker.ShowDialog();
                if (picker.DialogResult == DialogResult.OK)
                {
                    Contract contract = picker.SelectedObject as Contract;
                    if (contract != null)
                    {
                        this.contractNoLinkLabel.Text = contract.Address;
                        this.contractNoLinkLabel.Tag = contract;
                    }
                }
            }
        }


        private void newToolStripButton_Click(object sender, EventArgs e)
        {
            if (this._reminder != null && this._reminder.Id > 0)
                (new ReminderForm2()).Show();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor.Current = Cursors.Arrow;
                if (this.periedgroupBox.Visible)
                {
                    //周期生成
                    GetReminder();
                    this._reminders.Clear();
                    this._reminders = Reminder.GeneratePeriodReminder(
                        this._reminder,
                        (this.contractNoLinkLabel.Tag as Contract),
                        //GeneratePeriodReminder(this._reminder,
                        (int)this.advanceDaysUpDown.Value,
                        (int)this.periodMonthsUpDown.Value);

                    foreach (var item in this.Reminders)
                    {
                        Reminder.Insert(item);
                    }
                    if (this._generateReminders != null)
                    {
                        this._generateReminders(this.Reminders, (new EventArgs()));
                    }
                }
                else
                {
                    GetReminder();
                    if (this._reminder.Id < 1)
                    {
                        this._reminder.ReminderTime.AddDays(-(int)this.advanceDaysUpDown.Value);
                        Reminder.Insert(this._reminder);
                    }
                    else
                    {
                        Reminder.Update(this._reminder);
                    }
                    this.DisplayInfo();
                }
            }
            catch (Exception ex)
            {
                Logger.WriteError(BaseObjectTypes.Reminder, this._reminder, ex);
                MessageBox.Show("", "", MessageBoxButtons.OK);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            if (this._reminder == null || this._reminder.Id < 1)
                return;

            try
            {
                Cursor.Current = Cursors.Arrow;
                this._reminder.Delete();
            }
            catch (Exception ex)
            {
                Logger.WriteError(BaseObjectTypes.Reminder, this._reminder, ex);
                MessageBox.Show("删除出错", "客户删除！", MessageBoxButtons.OK);
            }
            finally
            {
                Cursor.Current = Cursors.Default;

            }
            this.Close();
        }

        private void cloneToolStripButton_Click(object sender, EventArgs e)
        {
            if (this._reminder != null && this._reminder.Id > 0)
            {
                ReminderForm2 form = new ReminderForm2((this._reminder.Clone()) as Reminder);
                form.Show();
            }
        }
    }
}
